<?php
namespace Api\Controller;
use Think\Controller\RestController;

/**
 * Movie Related Api Class
 *
 * @package Api\Controller
 * @author lythesia
**/
class MovieController extends RestController {
  protected $allowMethod = array('get');
  protected $allowType   = array('json', 'xml');

  /**
   * Get single movie information by `movie_id`
   *
   * @return mixed  return query results on `success` or error message on `fail`
   * @author lythesia
   **/
  public function info() {
    $mid = I('get.id', '', 'trim,filter_movieid');
    $default_field = 'id,title,aka,summary,producedby,budget,releasedate,filmlocation,country,runtime,genre,language,rating,ratingnum,mpaa,poster';
    $field = I('get.include', $default_field, 'trim');
    $format = I('get.format', 'json', 'trim,filter_api_format');
    $data = array();

    $data['status'] = 'fail';
    if(!$mid) {
      $data['msg'] = 'Invalid ID format, please check API manual.';
      goto end;
    }
    if($field !== '*' && !filter_movie_field($field)) {
      $data['msg'] = 'Invalid fields, please check API manual.';
      goto end;
    }
    if($format === false) {
      $data['msg'] = 'Invalid format, only `json` and `xml` are allowed.';
      $format = 'json';
      goto end;
    }

    $data['data'] = A('Common/Movie')->getMovieById($mid, $field);
    if($data['data']) {
      $data['status'] = 'success';
    }
    else {
      unset($data['data']);
      $data['msg'] = 'Database query failed or no result found.';
    }

    end:
    $this->response($data, $format);
  }

  /**
   * Get single movie with specified related information(e.g genres actors ..) by `movie_id`
   *
   * @return mixed return query results on `success` or error message on `fail`
   * @author lythesia
   **/
  public function info_rel() {
    $mid = I('get.id', '', 'trim,filter_movieid');
    $default_field = 'id,title,aka,summary,producedby,budget,releasedate,filmlocation,country,runtime,genre,language,rating,ratingnum,mpaa,poster';
    $field = I('get.include', $default_field, 'trim');
    $rel = I('get.rel', '', 'trim');
    $format = I('get.format', 'json', 'trim,filter_api_format');
    $data = array();

    $data['status'] = 'fail';
    if(!$mid) {
      $data['msg'] = 'Invalid ID format, please check API manual.';
      goto end;
    }
    if($field !== '*' && !filter_movie_field($field)) {
      $data['msg'] = 'Invalid fields, please check API manual.';
      goto end;
    }
    if($rel !== '' && !filter_movie_rel($rel)) {
      $data['msg'] = 'Invalid relation field, please check API manual.';
      goto end;
    }
    if($format === false) {
      $data['msg'] = 'Invalid format, only `json` and `xml` are allowed.';
      $format = 'json';
      goto end;
    }

    $opt = array(
      'rel' => explode(',', $rel),
    );
    $data['data'] = A('Common/Movie')->getMovieRelById($mid, $opt, $field);
    if($data['data']) {
      $data['status'] = 'success';
    }
    else {
      unset($data['data']);
      $data['msg'] = 'Database query failed or no result found.';
    }

    end:
    $this->response($data, $format);
  }

  /**
   * Search movies by (combinded) conditions
   *
   * @return mixed return query results on `success` or error message on `fail`
   * @author lythesia
   **/
  public function search() {
    $raw_cond = $_GET;
    $default_field = 'id,title,aka,summary,producedby,budget,releasedate,filmlocation,country,runtime,genre,language,rating,ratingnum,mpaa,poster';
    $field = I('get.include', $default_field, 'trim');
    $format = I('get.format', 'json', 'trim,filter_api_format');
    $data = array();
    $data['status'] = 'fail';

    $fmt_cond = array();
    $opt = array(
      'offset'  => 0,
      'size'    => 30,
    );

    foreach($raw_cond as $key => $val) {
      if($val) {
        switch($key) {
          /* title */
        case 'title':
          $title = I('get.title', '', 'trim,filter_query_str');
          if(!check_query_len($title)) {
            $data['msg']= 'Keywords in Title are too short.';
            goto end;
          }
          $fmt_cond['title,aka'] = $title;
          break;

          /* releasedate */
        case 'releasedate-min': case 'releasedate-max':
          $date = I('get.'.$key, false, 'trim,filter_date');
          if($date === false || !checkdate($date['mon'], $date['day'], $date['year'])) {
            $data['msg'] = 'Invalid input date, please check API manual.';
            goto end;
          }
          elseif($data === '') break 2;
          $date_new = $date['year'].'-'.$date['mon'].'-'.$date['day'];
          $fmt_cond['releasedate'][] = ($key == 'releasedate-min') ? 
            array('EGT', $date_new) : array('ELT', $date_new);
          break;

          /* rating */
        case 'rating-min': case 'rating-max':
          $rating = I('get.'.$key, false, 'float');
          if($rating === false) {
            $data['msg'] = 'Invalid input rating, please check API manual.';
            goto end;
          }
          $fmt_cond['rating'][] = ($key == 'rating-min') ?
            array('EGT', $rating) : array('ELT', $rating);
          break;

          /* runtime */
        case 'runtime-min': case 'runtime-max':
          $runtime = I('get.'.$key, false, 'int');
          if($runtime === false) {
            $data['msg'] = 'Invalid input runtime, please check API manual.';
            goto end;
          }
          $fmt_cond['runtime'][] = ($key == 'runtime-min') ?
            array('EGT', $runtime) : array('ELT', $runtime);
          break;

          /* genre[] */ 
        case 'genre':
          $fmt_cond['genre'] = implode(' ', $val);
          break;

          /* mpaa[] */
        case 'mpaa':
          if(!filter_movie_mpaa($val)) {
            $data['msg'] = 'Invalid input mpaa, please check API manual.';
            goto end;
          }
          $fmt_cond['mpaa'] = array('IN', $val);
          break;

          /* country */
        case 'country':
          $fmt_cond[$key] = $val;
          break;

          /* offset & size */
        case 'offset': 
          $opt[$key] = I('get.offset', 0, 'int');
          if($opt[$key] < 0) {
            $data['msg'] = 'Negative offset not allowd.';
            goto end;
          }
          break;
        case 'size':
          $opt[$key] = I('get.size', 30, 'int');
          if($opt[$key] <= 0) {
            $data['msg'] = 'Non-positive size not allowd.';
            goto end;
          }
          break;
        }
      }
    }
    if(!$fmt_cond) {
      $data['msg'] = 'Must specify at least one field.';
      goto end;
    }
    if($field !== '*' && !filter_movie_field($field)) {
      $data['msg'] = 'Invalid fields, please check API manual.';
      goto end;
    }
    if($format === false) {
      $data['msg'] = 'Invalid format, only `json` and `xml` are allowed.';
      $format = 'json';
      goto end;
    }

    $data['data'] = A('Common/Movie')->getMoviesByCond($fmt_cond, $opt, $field);
    // check if sql correct
    //$data['sql'] = M()->getLastSql();
    if($data['data']) {
      $data['status'] = 'success';
    }
    else {
      unset($data['data']);
      $data['msg'] = 'Database query failed or no result found.';
    }

    end:
      $this->response($data, $format);
  }
}
